package com.wosiliujing.learning.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.wosiliujing.learning.admin.SysLogDTO;
import com.wosiliujing.learning.constant.CommonConstants;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author: liujing
 * @date: 2019/5/17 19:55
 * @description:
 */
public class SysLogUtil {

    /**
     * 获取日志信息
     * @return 日志信息
     */
    public static SysLogDTO getSysLog(){
        HttpServletRequest request = ((ServletRequestAttributes) Objects
                .requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        SysLogDTO sysLog = new SysLogDTO();
        sysLog.setCreateUserName(getUserName());
        sysLog.setClientId(getClientId());
        sysLog.setCreateTime(LocalDateTime.now());
        sysLog.setRequestUrl(request.getRequestURI());
        sysLog.setIp(ServletUtil.getClientIP(request));
        sysLog.setMethod(request.getMethod());
        sysLog.setUserAgent(request.getHeader("user-agent"));
        sysLog.setDelFlag(CommonConstants.NORMAL_STATUS);
        return sysLog;
    }

    /**
     * 获取资源服务器ClientId
     * @return ClientId
     */
    private static String getClientId(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication instanceof OAuth2Authentication){
            OAuth2Authentication auth2Authentication = (OAuth2Authentication) authentication;
            return auth2Authentication.getOAuth2Request().getClientId();
        }
        return null;
    }

    /**
     * 获取用户名
     * @return 用户名
     */
    private static String getUserName(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(ObjectUtil.isNotEmpty(authentication)){
            return  authentication.getName();
        }
        return  null;
    }
}
